package com.atguigu.yygh.hosp.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoDbConfig {

    /**
     * 删除_class 属性的配置
     * MongoDB-->yygh_hosp数据库表(Department,Hospital,Schedule)
     * 在这解释一下这个方法的意义,因为MongoDB数据库中这几张表的数据,我为了练习代码,反复的删除又增加过,
     * Example<Department> example = Example.of(departmentQuery);
     * 结果导致就是MongoRepository.findAll(example)方法加上example条件根据hoscode医院编号
     * 去查的时候,默认MongoRepository会有一个_class属性去查询,就是因为_class属性不对。
     * 因为反复删除添加表的原因,一开始存储表的实体类全类名和现在的实体类全类名不一致
     * 所以查不到数据.这里需要禁用_class属性配置
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {

        }
        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }

}
